package com.itheima.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@RestController
@Slf4j
@RequestMapping("dish")
public class DishController {
   @Autowired
    DishService dishService;

   @Autowired
   DishFlavorService dishFlavorService;

   @Autowired
    CategoryService categoryService;

   @Autowired
    RedisTemplate redisTemplate;


   @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
     // System.out.println("dishDto = " + dishDto);
       dishService.saveWithFlavor(dishDto);
       //清除缓存
       redisTemplate.delete("dishList_"+dishDto.getCategoryId());
       return R.success("增加菜品成功!");

    }

    @GetMapping("page")
    public R<Page<DishDto>>  page(Integer page,Integer pageSize,String name){
        Page<Dish> pageInfo1 = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> wrapper = Wrappers.lambdaQuery(Dish.class)
                .like(StringUtils.isNotBlank(name),Dish::getName, name)
                .orderByAsc(Dish ::getSort)
                .orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo1,wrapper);

        Page<DishDto> pageInfo2 = new Page<>(page, pageSize);
        //复制dish表中的菜品数据,除开category_id
        BeanUtils.copyProperties(pageInfo1,pageInfo2,"records");

        List<DishDto> dishDtoList=pageInfo1.getRecords().stream().map(dish -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(dish, dishDto);
            Category category = categoryService.getById(dish.getCategoryId());
            dishDto.setCategoryName(category.getName());
            return dishDto;
        }).collect(Collectors.toList());


        pageInfo2.setRecords(dishDtoList);
        return R.success(pageInfo2);


    }
     //id回显查询
    @GetMapping("{id}")
    public R<DishDto> getById(@PathVariable Long id){
       DishDto dishDto = dishService.getByIdWithFlavor(id);
       return R.success(dishDto);
    }
    //套餐页中,根据分类查询菜品
    @GetMapping("list")
    public R<List<DishDto>> list(Dish dish){
       //1. 新建redis 唯一key
        String redisKey="dishList_"+dish.getCategoryId();
        List<DishDto> redisDish = (List<DishDto>) redisTemplate.opsForValue().get(redisKey);
        if (redisDish != null) {
            return R.success(redisDish);
        }
        LambdaQueryWrapper<Dish> queryWrapper = Wrappers.lambdaQuery(Dish.class)
                .eq(dish.getCategoryId()!=null,Dish::getCategoryId, dish.getCategoryId())
                .eq(Dish ::getStatus,1)
                .orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(queryWrapper);
        List<DishDto> dtoList = new ArrayList<>();
        for (Dish item : list) {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            LambdaQueryWrapper<DishFlavor> wrapper = Wrappers.lambdaQuery(DishFlavor.class)
                    .eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> dishFlavorList = dishFlavorService.list(wrapper);
            dishDto.setFlavors(dishFlavorList);
            dtoList.add(dishDto);
        }
        redisTemplate.opsForValue().set(redisKey,dtoList);
        return R.success(dtoList);
    }

    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
      dishService.updateWithFlavor(dishDto);
        redisTemplate.delete("dishList_"+dishDto.getCategoryId());
      return R.success("修改成功!");
    }

    @DeleteMapping
    public R<String>delete( Long[] ids) {
     dishService.deleteWithFlavor(ids);
        for (Long id : ids) {
            redisTemplate.delete("dishList_"+id);
        }

     return R.success("删除成功!");
    }

    //更改菜品状态(启用/禁用)
    @PostMapping("status/{status}")
    public R<String> status(@PathVariable Integer status,Long[] ids){
       dishService.updateStatus(status, ids);
        return R.success("更改菜品状态成功!");
    }
}
